package ar.com.gep.soccer.frontend.lazydatamodels;

import java.util.List;
import java.util.Map;

import org.jboss.logging.Logger;
import org.primefaces.model.SortOrder;

import ar.com.cdt.framework.business.exception.CDTFrameworkBusinessException;
import ar.com.cdt.framework.core.pager.ResultSet;
import ar.com.gep.soccer.services.TeamService;
import ar.com.gep.soccer.services.dto.TeamDTO;

public class TeamLazyDataModel extends BaseLazyDataModel<TeamDTO> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1922528142214210915L;

	private static final Logger log = Logger.getLogger(TeamLazyDataModel.class);
	private static String TABLE_NAME = "team";

	private ResultSet<TeamDTO> teams;
	private TeamService teamService;

	/**
	 * 
	 * @param teamService
	 */
	public TeamLazyDataModel(TeamService teamService) {
		super();
		this.teamService = teamService;
	}

	@Override
	public Object getRowKey(TeamDTO team) {
		return team.getId();
	}

	@Override
	public TeamDTO getRowData(String id) {
		for (TeamDTO category : teams.getResult()) {
			if (category.getId().equals(Long.valueOf(id))) {
				return category;
			}
		}
		return null;
	}

	@Override
	public List<TeamDTO> load(int startingAt, int maxPerPage, String sortField, SortOrder sortOrder, Map<String, String> filters) {
		log.infov("TeamLazyDataModel - load(): Obteniendo registros de la tabla {0}", TABLE_NAME);
		try {
			teams = teamService.getAll(getPage(startingAt, maxPerPage, sortField, sortOrder));
			if (getRowCount() <= 0) {
				setRowCount(teams.getTotalResults());
			}

			return teams.getResult();
		} catch (CDTFrameworkBusinessException e) {
			log.errorv("TeamLazyDataModel - load(): Ocurrio un error. Causa: {1}", e);
			return null;
		}
	}

	public ResultSet<TeamDTO> getTeams() {
		return teams;
	}

	public void setTeams(ResultSet<TeamDTO> teams) {
		this.teams = teams;
	}

}
